package com.javaee.xiangyang.controller.mall;

import com.javaee.xiangyang.common.ServiceResultEnum;
import com.javaee.xiangyang.dto.OrderGoods;
import com.javaee.xiangyang.entity.Order;
import com.javaee.xiangyang.entity.User;
import com.javaee.xiangyang.service.AccountService;
import com.javaee.xiangyang.service.OrderService;
import com.javaee.xiangyang.vo.ServerResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.ModelAndViewMethodReturnValueHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/MallOrder")
public class MallOrderController {

    @Resource
    OrderService orderService;

    @Resource
    AccountService accountService;

    /**
     * 前往订单查看页面
     */
    @RequestMapping("/ToOrder")
    public ModelAndView findAllOrder(ModelAndView modelAndView, HttpSession session) {
        User user = (User) session.getAttribute("user");
        //找到该用户的所有订单
        List<OrderGoods> orderByUserAccount = orderService.findOrderByUserAccount(new Order(user.getUserAccount()));
        modelAndView.addObject("orders", orderByUserAccount);
        modelAndView.setViewName("/mall/customer-order");
        return modelAndView;
    }

    /**
     * 订单状态改变
     */
    @RequestMapping("/UpdateOrder")
    public ModelAndView updateOrderState(ModelAndView modelAndView, Order order) {
        ServiceResultEnum serviceResultEnum = orderService.updateOrderStateByOrderId(order);
        if (serviceResultEnum == ServiceResultEnum.SUCCESS){
            modelAndView.setViewName("redirect:/MallOrder/ToOrder");
            return modelAndView;
        }
        modelAndView.addObject("error", serviceResultEnum.getResult());
        modelAndView.setViewName("/error/error");
        return modelAndView;
    }

    /**
     * 按照购物车信息成订单
     */
    @RequestMapping("/AddOrder")
    public ModelAndView addOrder(ModelAndView modelAndView, Order order, HttpSession session) {
        User user = (User) session.getAttribute("user");
        order.setOrderUserAccount(user.getUserAccount());
        //重置时间
        order.setOrderStart(new Date());
        ServiceResultEnum serviceResultEnum = orderService.insertOrder(order);
        if (serviceResultEnum == ServiceResultEnum.SUCCESS) {
            //如果成功
            //刷新session
            session.removeAttribute("user");
            session.setAttribute("user", accountService.GetUser(new User(user.getUserAccount())));
            modelAndView.setViewName("redirect:/MallGoods/index");
            return modelAndView;
        }
        //失败
        modelAndView.addObject("error", serviceResultEnum.getResult());
        modelAndView.setViewName("/error/error");
        return modelAndView;
    }

}
